package com.leo.ibatis.demo.web.controller;

import java.util.LinkedHashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.validation.BindException;
import org.springframework.web.bind.ServletRequestDataBinder;
import org.springframework.web.bind.ServletRequestUtils;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;

import com.leo.ibatis.demo.criteria.InventoryCriteria;
import com.leo.ibatis.demo.domain.Inventory;
import com.leo.ibatis.demo.service.InventoryService;

public class InventoryFormController extends SimpleFormController {

	private InventoryService inventoryService;

	public void setInventoryService(InventoryService inventoryService) {
		this.inventoryService = inventoryService;
	}

	@Override
	@SuppressWarnings("unchecked")
	protected Map referenceData(HttpServletRequest request) throws Exception {
		String mode = ServletRequestUtils.getRequiredStringParameter(request, "mode");
		
		InventoryCriteria inventoryCriteria = new InventoryCriteria();
		ServletRequestDataBinder binder = createBinder(request, inventoryCriteria);
		binder.bind(request);
		
		Map map = new LinkedHashMap();
		map.put("mode",  mode);
		map.put("inventoryCriteria", inventoryCriteria);

		return map;
	}

	@Override
	protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception {
	}

	@Override
	protected void onBind(HttpServletRequest request, Object command, BindException errors) throws Exception {
	}

	@Override
	protected void onBindAndValidate(HttpServletRequest request, Object command, BindException errors) throws Exception {
	}

	@Override
	protected Object formBackingObject(HttpServletRequest request) throws Exception {
		Inventory inventory = null;
		
		String mode = ServletRequestUtils.getRequiredStringParameter(request, "mode");

		if (mode.equals("write")) {
			inventory = new Inventory();
		}
		
		if (mode.equals("edit")) {
			String itemid = ServletRequestUtils.getRequiredStringParameter(request, "itemid");

			inventory = inventoryService.select(itemid);
		}

		return inventory;
	}

	@Override
	protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception {
		String mode = ServletRequestUtils.getRequiredStringParameter(request, "mode");
		
		Inventory inventory = (Inventory) command;
		
		if (mode.equals("write")) {
			inventoryService.insert(inventory);
		} else if (mode.equals("edit")) {
			inventoryService.update(inventory);
		}

		return new ModelAndView(getSuccessView());
	}

}
